package com.alex.config;

import com.alex.dao.Person;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 对于响应之前的处理
 */
@RestControllerAdvice
public class CustomerResponseAdvise implements ResponseBodyAdvice {

    /**
     * 对于什么样的参数进行拦截
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return methodParameter.hasMethodAnnotation(ProcessTag.class);
    }

    /**
     * 对响应体进行处理
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof Person) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("person", body);
            map.put("extra-body", "demo-body");

            return map;
        }

        return body;
    }
}
